package com.das.mechanic_base.mapi.api;


import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.bean.common.LocaleBean;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3LogUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by chensi on 2018/3/16.
 */
public class NetWorkHttp {
    //public static final String API_BASE_URL = Constent.BASE_URL;//主Api路径

    private static Retrofit mRetrofit;
    public static OkHttpClient mOkHttpClient;

    private static Retrofit mGeneralRetrofit;
    private static OkHttpClient mGeneralOkHttpClient;

    private static Retrofit mLiveRetrofit;
    private static OkHttpClient mLiveOkHttpClient;

    private static Retrofit mLanguageRetrofit;
    private static OkHttpClient mLanguageOkHttpClient;

    public final static int CONNECT_TIMEOUT = 60 * 60;        //设置连接超时时间
    public final static int READ_TIMEOUT = 60 * 60;            //设置读取超时时间
    public final static int WRITE_TIMEOUT = 60 * 60;           //设置写的超时时间

    public static OkHttpClient genericClient() {
        //OkHttp3拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(message -> {
            boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
//            if (!isSdk) {
//                X3LogUtils.i(message);
//            }
            X3LogUtils.i(message);
        });

        //Okhttp3的拦截器日志分类 4种
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        /**
         * 添加网络缓存
         */
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                .addInterceptor(chain -> {
                    LocaleBean appLocale = LanguageUtiles.getAppLocale(LanguageUtiles.appContext);

                    String appVersionName = "";
                    String deviceInfo = "";
                    String osVersion = "";

                    try {
                        osVersion =  android.os.Build.VERSION.RELEASE;
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        //制造商 （Manufacturer）,型号（Model）,品牌（Brand）,设备名 （Device）
                        deviceInfo  =  android.os.Build.MANUFACTURER + "|" + android.os.Build.MODEL + "|" + android.os.Build.BRAND + "|" + android.os.Build.DEVICE;
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    try {
                        appVersionName = X3MyApp.getInstance().getApp().getPackageManager().getPackageInfo(X3MyApp.getInstance().getApp().getPackageName(),0).versionName;
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    //Log.e("SSSS","请求网络:"+appLocale.getLanguage() + "_" + appLocale.getCountry());
                    Request request = chain.request().newBuilder()
                            .addHeader("Content-Type","application/json;charset=utf-8")
                            .addHeader("Authorization", SpHelper.getData("token", "") + "")
                            .addHeader("device-model", Build.MODEL)
                            .addHeader("Accept-Language",appLocale.locale.getLanguage() + "-" + appLocale.locale.getCountry())
                            .addHeader("os-version", Build.VERSION.RELEASE)
                            .addHeader("Autox3AppVersion", appVersionName)
                            .addHeader("Autox3MobileType", deviceInfo)
                            .addHeader("Autox3OSVersion", osVersion)
                            .addHeader("x-request-time", System.currentTimeMillis()+"")
                            .addHeader("timezone", TimeZone.getDefault().getID())
                            .addHeader("MileageUnit", (String) SpHelper.getData(X3Constent.MILEAGEUNIT,"km"))
                            .addHeader("CurrencyCode", (String) SpHelper.getData(X3Constent.MONEYUNIT,"CNY"))
                            .build();

                    return chain.proceed(request);
                })
                .build();
        String s = "abbbb";
        s.indexOf("b");
        return httpClient;
    }

    public static ApiService getApi() {
        return getRetrofit().create(ApiService.class);
    }

    public static ApiService getLiveApi() {
        return getLiveRetrofit().create(ApiService.class);
    }

    public static ApiService getGeneralApi() {
        return getGeneralRetrofit().create(ApiService.class);
    }

    protected static Retrofit getRetrofit() {

        if (null == mOkHttpClient) {
            mOkHttpClient = genericClient();
        }
        System.out.println("现在的地址"+ SpHelper.getData(X3Constent.BASE_URL_SAVE, X3Constent.getBaseUrlByAreaCode()));
        mRetrofit = new Retrofit.Builder()
                .baseUrl((String) SpHelper.getData(X3Constent.BASE_URL_SAVE, X3Constent.getBaseUrlByAreaCode()))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mOkHttpClient)
                .build();
        return mRetrofit;
    }

    /**
     * 通用服务器
     * @return
     */
    protected static Retrofit getGeneralRetrofit() {

        if (null == mGeneralRetrofit) {
            if (null == mGeneralOkHttpClient) {
                mGeneralOkHttpClient = genericClient();
            }
            mGeneralRetrofit = new Retrofit.Builder()
                    .baseUrl(X3Constent.getBaseGeneralUrl())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(mGeneralOkHttpClient)
                    .build();
        }

        return mGeneralRetrofit;
    }

    /**
     * 直播
     * @return
     */
    protected static Retrofit getLiveRetrofit() {

        if (null == mLiveRetrofit) {
            if (null == mLiveOkHttpClient) {
                mLiveOkHttpClient = genericClient();
            }
            mLiveRetrofit = new Retrofit.Builder()
                    .baseUrl((String) SpHelper.getData(X3Constent.BASE_URL_LIVE_SAVE, X3Constent.getBaseUrlByAreaCode()))
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(mLiveOkHttpClient)
                    .build();
        }

        return mLiveRetrofit;
    }

    public static ApiService getLanguageApi() {
        return getLanguageRetrofit().create(ApiService.class);
    }

    protected static Retrofit getLanguageRetrofit() {

        if (null == mLanguageOkHttpClient) {
            mLanguageOkHttpClient = genericClient();
        }
        mLanguageRetrofit = new Retrofit.Builder()
                .baseUrl("https://translate.autox3.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mLanguageOkHttpClient)
                .build();

        return mLanguageRetrofit;
    }

}
